package cn.xutongxue.doc.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.xutongxue.common.enums.Errors;
import cn.xutongxue.common.excption.BusinessException;
import cn.xutongxue.common.utils.ThrowUtils;
import cn.xutongxue.doc.config.CosClientConfig;
import cn.xutongxue.doc.module.dto.DocUploadResultDto;
import com.qcloud.cos.model.PutObjectResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FileUtil {

    private final CosClientConfig cosClientConfig;
    private final CosUtil cosUtil;

    /**
     * 上传文档
     * @param multipartFile
     * @param uploadPathPrefix 文件上传前缀
     * @return
     */
    public DocUploadResultDto uploadDoc(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验文件
        validDoc(multipartFile);
        // 生成文件上传路径
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s",
                DateUtil.formatDate(new Date()),
                uuid,
                cn.hutool.core.io.FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        // 上传文件
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosUtil.putObject(uploadPath, file);
            // 封装返回结果
            DocUploadResultDto docUploadResultDto = new DocUploadResultDto();
            docUploadResultDto.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            docUploadResultDto.setFilename(cn.hutool.core.io.FileUtil.mainName(originalFilename));
            docUploadResultDto.setFileSize(cn.hutool.core.io.FileUtil.size(file));
            docUploadResultDto.setFileFormate(cn.hutool.core.io.FileUtil.getSuffix(file));
            return docUploadResultDto;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(Errors.INTERNAL_SERVER_ERROR, "文件上传失败");
        } finally {
            // 删除临时文件
            deleteTemplateFile(file);
        }

    }


    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private void validDoc(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, Errors.PARAMS_ERROR, "文件不能为空");
        long size = multipartFile.getSize();
        // 文件大小校验
        final long MAX_FILE_SIZE = 1024 * 1024 * 100;
        ThrowUtils.throwIf(size > MAX_FILE_SIZE, Errors.PARAMS_ERROR, "文件大小不能超过100M");
        // 检查文件后缀
        String fileSuffix = cn.hutool.core.io.FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_FILE_SUFFIX = Arrays.asList("doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf");
        ThrowUtils.throwIf(!ALLOW_FILE_SUFFIX.contains(fileSuffix), Errors.PARAMS_ERROR, "文件格式不支持");
    }

    /**
     * 删除临时文件
     *
     * @param file
     */
    public void deleteTemplateFile(File file) {
        if (file != null) {
            boolean result = file.delete();
            if (!result) {
                log.error("删除临时文件失败, filepath = " + file.getAbsolutePath());
            }
        }
    }
}
